package org.example.producer;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutionException;

/**
 * 带拦截器的生产者
 * @ClassName InterceptorProducer
 * @Author 小坏
 * @Date 2021/11/3、17:31
 * @Version 1.0
 */
public class InterceptorProducer {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Properties properties = new Properties();

        //指定连接的kafka集群
        properties.put("bootstrap.servers", "hadoop102:9092");

        //Ack应答级别
        properties.put("acks", "all");

        //重试次数
        properties.put("retries", 3);

        //批次大小
        properties.put("batch.size", 16384);

        //等待时间
        properties.put("linger.ms", 1);

        properties.put("buffer.memory", 33554432);
        //RecordAccumulator 缓 冲区大小
        properties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        properties.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

        //加入拦截器
        List<String> list =  new ArrayList<>();
        list.add("org.example.interceptor.TimeInterceptor");
        list.add("org.example.interceptor.CounterInterceptor");
        properties.put(ProducerConfig.INTERCEPTOR_CLASSES_CONFIG,list);

        KafkaProducer<String, String> producer = new KafkaProducer<>(properties);


        /**
         * 使用最后的一个api、只有一个key、所有他自己取轮询
         */
        for (int i = 0; i < 10; i++) {
            producer.send(new ProducerRecord<>("first", "atguigu","atguigu-" + i)).get();
        }

        //关闭资源
        producer.close();
    }
}
